package cn.nju.zyy.hello;

import java.util.Iterator;
import java.util.List;

import javax.persistence.EntityManager;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.ejb.HibernateEntityManager;

import cn.nju.zyy.persistence.JPAUtil;

public class HibernateStyleHelloWorld {

	public static void main(String[] args) {
		listMessages();
	}

	public static void listMessages() {
		// Second unit of work
		EntityManager em = JPAUtil.getEntityManagerFactory()
				.createEntityManager();
		HibernateEntityManager hem = (HibernateEntityManager) em;
		Session newSession = hem.getSession();
		Transaction newTransaction = newSession.beginTransaction();

		List messages = newSession.createQuery(
				"from Message m order by m.text asc").list();

		System.out.println(messages.size() + " message(s) found: ");

		for (Iterator iter = messages.iterator(); iter.hasNext();) {
			Message loadedMsg = (Message) iter.next();
			System.out.println(loadedMsg.getText());
		}

		newTransaction.commit();
		newSession.close();
	}

}
